Python Project Fetch & Process API Data
✅ Python Project : Fetch & Process API Data 🌍📡
📌 Task:
Create a Python program that fetches data from a public API, processes it, and stores it in a JSON file.
🧠 What You’ll Learn:
-
How to make GET requests using the
requestsmodule -
How to read API responses (JSON format)
-
How to save useful data into a JSON file
✅ Python Code Example
import requests
import json
# Step 1: API endpoint (Example: Random User API)
url = "https://randomuser.me/api/?results=5"
# Step 2: Fetch data from API
response = requests.get(url)
# Step 3: Check if request was successful
if response.status_code == 200:
data = response.json()
print("✅ API Data Fetched Successfully!\n")
# Print raw API data
print(json.dumps(data, indent=4))
# Step 4: Process data (get only names & emails)
users = []
for user in data["results"]:
users.append({
"name": f"{user['name']['first']} {user['name']['last']}",
"email": user["email"]
})
# Step 5: Save processed data into JSON
with open("users.json", "w") as f:
json.dump(users, f, indent=4)
print("\n✅ Processed data saved in users.json")
else:
print(f"❌ Error: Could not fetch data (Status: {response.status_code})")
📥 How It Works:
-
Sends a request to an API (
randomuser.me) -
Gets response in JSON format
-
Extracts useful info (name & email)
-
Saves it into
users.json
🔧 Try Yourself:
-
Fetch weather, news, or crypto data using another API
-
Change query parameters (e.g., number of users, location)
-
Schedule script to run daily and save logs
💡 Where You Can Use It:
✅ Collecting data for dashboards
✅ Real-time apps (news, stock, weather)
✅ Automating daily reports
Comments
Post a Comment